package com.ruoyi.whzj.controller;


import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.*;

import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.whzj.domain.*;
import com.ruoyi.whzj.service.*;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.awt.*;
import java.util.*;
import java.util.List;


/**
 * 快手接口控制器
 */
@Controller
@RequestMapping(value = "/phone/whzj/svApi")
public class SvApiController extends BaseController {

    @Autowired
    private IWhUserService whUserService;

    @Autowired
    private IWhTasksettingService whTasksettingService;

    @Autowired
    private IWhTaskService whTaskService;

    @Autowired
    private IWhTaskUserService whTaskUserService;

    @Autowired
    private IWhIntegralHistoryService whIntegralHistoryService;

    @Autowired
    private IWhzjBaseconfigService whzjBaseconfigService;

    @Autowired
    private IWhUserLittleService whUserLittleService;

    private static Map<String ,Object> kMap = new HashMap<>();

    private static String appId = "1602568065626";

    private static String appKey = "d805ec90f09684fbd86550deffbe476a";

    public static void main(String args[])throws Exception{

        String str = "1,2,3,4,5,6";//，号分割的字符串
        String[] strarr = str.split(",");//拆分成字符串数组
        for(int i=0;i<100;i++){
            Random random = new Random();//随机对象
            int n = random.nextInt(strarr.length);//随机一个整数
            System.out.println(strarr[n]);
        }

//        String number = "2111861224";
////        String url = "https://svapi.yokey.top/api/v1/?appId="+appId+"&appKey="+appKey+"&action=gifshow/search/user&keyword="+number+"&pCursor=&usSid=";
////        String url1 = "https://svapi.yokey.top/api/v1/?appId="+appId+"&appKey="+appKey+"&action=gifshow/user/profile&uid="+number;
//////        String json = HttpUtils.sendGet(url, "");
//////        String json = sendGet(url);
////        String json = OkHttpUtil.get(url1);
////        System.out.println("返回结果---------------------"+json);
////        JSONObject jsonObject = JSONObject.fromObject(json);
////        System.out.println(jsonObject);
////
//////        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
//////                .followRedirects(true)
//////                .build();
//////        System.out.println(url);
//////        Request request = new Request.Builder().url(url).get().build();
//////       Response response = okHttpClient.newCall(request).execute();
//////       System.out.println(response.code());
//////       System.out.println(response.body().string());
////
////
//////        Map<String, Object> map = JSON.parseObject(json, new TypeReference<Map<String, Object>>() {});
//////        List<Object> users = (List)jsonObject.get("users");
//////        System.out.println(users);
//////        if(users.size() > 0 ){
//////            Map<String, Object> user = (Map<String, Object>) users.get(0);
//////            String userId = user.get("user_id").toString();
//////            System.out.println("用户userId---------------------"+userId);
//////        }else{
//////            System.out.println("快手号不存在，请重新检查");
//////        }
////
////        Map<String, Object> userProfile = (Map<String, Object>)jsonObject.get("userProfile");
////
////        Map<String, Object> profile = (Map<String, Object>) userProfile.get("profile");
////        String userName = profile.get("user_name").toString();
////        String headurl = profile.get("headurl").toString();
////        String kwaiId = profile.get("kwaiId").toString();
////        System.out.println(userName);
////        System.out.println(headurl);
////        System.out.println(kwaiId);
    }

    //获取分享连接
    public String getShareUrl(String kuaiId){
        String _shareUrl = "";
        try {

            String shareUrl = "https://svapi.yokey.top/api/v1/?appId="+appId+"&appKey="+appKey+"&action=gifshow/share/profile&uid="+kuaiId;
            String shareJson = OkHttpUtil.get(shareUrl);
            System.out.println("返回结果---------------------"+shareJson);
            JSONObject shareJsonObject = JSONObject.fromObject(shareJson);
            System.out.println(shareJson);
            List<Map<String, Object>>  sharePlatformDataList = ( List<Map<String, Object>>)shareJsonObject.get("sharePlatformDataList");
            Map<String, Object> shareConfig = (Map<String, Object>)sharePlatformDataList.get(0).get("shareConfig");
            _shareUrl = shareConfig.get("shareUrl").toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return _shareUrl;
    }

    /**
     * 获取快手id
     * @param number 快手id
     * @param pCode
     * @return
     */
    @RequestMapping("/getKuaiId")
    @ResponseBody
    public AjaxResult getKuaiId(String number, String pCode)throws Exception
    {
        WhzjBaseconfig whzjBaseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");
        String userId = number;
        WhUser whUser = whUserService.selectWhUserByKuaiId(userId);

        if(whUser == null){

            whUser = whUserService.selectWhUserByKuaiNumber(number);
            if(whUser != null){
                return success("操作成功", whUser);
            }

            String url = "https://svapi.yokey.top/api/v1/?appId="+appId+"&appKey="+appKey+"&action=gifshow/search/user&keyword="+number+"&pCursor=&usSid=";

            long time = System.currentTimeMillis();
            String json = "";
            do{
                try {

                    long time1 = System.currentTimeMillis();
                    if(time1 - time > 55 * 1000){
                        return error("请求超时，请刷新后重试");
                    }

                    json = OkHttpUtil.get(url);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }while (EmptyUtils.isEmpty(json));


            System.out.println("返回结果---------------------"+json);
            whUser = new WhUser();
            try{
                JSONObject jsonObject = JSONObject.fromObject(json);
                List<Map<String, Object>>  users = ( List<Map<String, Object>>)jsonObject.get("users");
                String kuaiUserId = String.valueOf(users.get(0).get("user_id"));
                String kwaiId = String.valueOf(users.get(0).get("kwaiId"));
                String headurl = String.valueOf(users.get(0).get("headurl"));
                String user_name = String.valueOf(users.get(0).get("user_name"));
                whUser.setHeadImg(headurl);
                whUser.setNickname(user_name);
//                whUser.setKuaiNumber(number);
                whUser.setKuaiId(kuaiUserId);
                if(EmptyUtils.isNotEmpty(kwaiId)){
                    whUser.setKuaiNumber(kwaiId);
                }else{
                    whUser.setKuaiNumber(kuaiUserId);
                }
                System.out.println(kuaiUserId);
                if(!kuaiUserId.equals(number) && !kwaiId.equals(number)){
                    return error("快手号不存在，请重新输入");
                }
            }catch (Exception e){
                e.printStackTrace();
                return error("操作失败");
            }


            whUser.setId(IdWorker.getId());
            whUser.setCreateTime(new Date());
            whUser.setNextReceiveTime(new Date());
            whUser.setIntegral(whzjBaseconfig.getFirstSend());
            whUser.setInvitationCode(StringUtils.getRandomString(6));
            whUser.setpCode("0");
            //根据父级邀请码查下父级是否存在
            WhUser userP = whUserService.selectWhUserByCodeId(pCode);
            if(userP != null){
                whUser.setpCode(pCode);
                whUser.setpPCode(userP.getpCode());


                WhUser userP1 = new WhUser();
                userP1.setId(userP.getId());
                userP1.setIntegral(userP.getIntegral() + whzjBaseconfig.getShareSend());
                List<WhUser> list = whUserService.selectWhUserByPCode(pCode);
                if(list.size() >= whzjBaseconfig.getAutoRiselevel()){
                    userP1.setUserGroup("代理用户");
                    if(EmptyUtils.isEmpty(userP.getCommission())){
                        userP1.setCommission(whzjBaseconfig.getFirstDistrirate().toString());
                        userP1.setSecondDistirrate(whzjBaseconfig.getSecondDistirrate().toString());
                    }
                }
                whUserService.updateWhUser(userP1);

                //积分记录
                WhIntegralHistory history = new WhIntegralHistory();
                history.setId(IdWorker.getId());
                history.setCreateTime(new Date());
                history.setUserId(userP.getId());
                history.setIntegral(whzjBaseconfig.getShareSend());
                history.setEventId(null);
                history.setOperat("11");
                whIntegralHistoryService.insertWhIntegralHistory(history);

            }

            //积分记录
            WhIntegralHistory history = new WhIntegralHistory();
            history.setId(IdWorker.getId());
            history.setCreateTime(new Date());
            history.setUserId(whUser.getId());
            history.setIntegral(whzjBaseconfig.getFirstSend());
            history.setEventId(null);
            history.setOperat("12");
            whIntegralHistoryService.insertWhIntegralHistory(history);

            whUserService.insertWhUser(whUser);


        }

        return success("操作成功", whUser);

    }


    /**
     * 获取快手id
     * @param number 快手id
     * @return
     */
    @RequestMapping("/getKuaiIdByNumber")
    @ResponseBody
    public AjaxResult getKuaiIdByNumber(String number)throws Exception
    {
        WhzjBaseconfig whzjBaseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");
        String[] svapis = whzjBaseconfig.getSvapi().split(",");
        Random random = new Random();//随机对象
        int n = random.nextInt(svapis.length);//随机一个整数
        String svapiId = svapis[n];

        String url = "http://182.254.153.170:8000/gifshow/search/user?infoId="+svapiId+"&proxyId=1&keyword="+number;

        String json = "";

        json = OkHttpUtil.get(url);
        if(!json.contains(number)){
            return error("快手号不存在");
        }
        JSONObject jsonObject = JSONObject.fromObject(json);
        List<Map<String, Object>>  users = ( List<Map<String, Object>>)jsonObject.get("users");
        String kuaiUserId = String.valueOf(users.get(0).get("user_id"));//快手id
        String kwaiId = String.valueOf(users.get(0).get("kwaiId"));//快手号
        if(!kuaiUserId.equals(number)){
            if(!kwaiId.equals(number)){
                return error("快手号不存在");
            }
        }

        return success("快手号存在");

//        JSONObject jsonObject = JSONObject.fromObject(json);
//        List<Map<String, Object>>  users = ( List<Map<String, Object>>)jsonObject.get("users");
//        kuaiUserId = String.valueOf(users.get(0).get("user_id"));//快手id
//        kwaiId = String.valueOf(users.get(0).get("kwaiId"));//快手号
//        String headurl = String.valueOf(users.get(0).get("headurl"));
//        String user_name = String.valueOf(users.get(0).get("user_name"));








    }


    /**
     * 判断用户是否点赞成功 -- 并登陆
     * @param number
     * @param pCode
     * @param photoId
     * @param taskId
     * @return
     * @throws Exception
     */
    @RequestMapping("/userLogin")
    @ResponseBody
    public synchronized AjaxResult userLogin(String number, String pCode, String photoId, String taskId)throws Exception
    {

        WhUser whUserNew = getKId(number);

        WhUser whUser = whUserService.selectWhUserByKuaiId(number);

        if(whUser == null){
            whUser = whUserService.selectWhUserByKuaiNumber(number);
        }
        if(whUser == null){
            whUser = whUserNew;
        }
        if(whUser == null){
            whUser = getKIdByAll(number);
            whUserNew = whUser;
            if(whUser == null){
                return error("验证失败，请重试");
            }
        }



        String kId = whUser.getKuaiId();
        WhTask task = whTaskService.selectWhTaskById(taskId);
        int allNum = task.getAllNum();
        int num = task.getNum();

        WhzjBaseconfig whzjBaseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");
        String[] svapis = whzjBaseconfig.getSvapi().split(",");
        Random random = new Random();//随机对象
        int n = random.nextInt(svapis.length);//随机一个整数
        String svapiId = svapis[n];
        String url = "http://182.254.153.170:8000/gifshow/moment/list?infoId="+svapiId+"&proxyId=1&uid="+whUser.getKuaiId();



        String json = OkHttpUtil.get(url);
        System.out.println("返回结果---------------------"+json);
        boolean isContains = false;
        if(!json.contains(photoId)){
            String workId = task.getWorkId();
            String url1 = "http://47.94.111.161:9106/api/v1/kuaishou/user/photos/info?token=0f400461-227b-45bc-98d2-bbdabb3f&photoIds="+workId;
            String json1 = OkHttpUtil.get(url1);
            JSONObject jsonObject = JSONObject.fromObject(json1);
            Map<String, Object>  data = ( Map<String, Object>)jsonObject.get("data");
            Map<String, Object>  photos = ( Map<String, Object>) data.get("photos");
            Map<String, Object>  work = ( Map<String, Object>) photos.get(workId);
            Integer likeNum = (int) work.get("like_count");
            if(task.getLikeNum() < likeNum){
                isContains = true;
            }
        }

        if(json.contains(photoId) || isContains){
            if(task != null){
                //任务完成数量+1
                WhTask task1 = new WhTask();
                task1.setId(taskId);
                task1.setNum(task.getNum() + 1);
                if(num + 1 == allNum){
                    task1.setStatus("已完成");
                }
                whTaskService.updateWhTask(task1);
            }

            if(EmptyUtils.isEmpty(whUser.getId())){//新增用户
                WhUser whUser1 = whUserService.selectWhUserByKuaiId(kId);

                if(whUser1 != null){
                    WhUser whUserUpdate = new WhUser();
                    whUserUpdate.setId(whUser1.getId());
                    whUserUpdate.setLoginnum(whUser1.getLoginnum() + 1);
                    whUserUpdate.setHeadImg(whUserNew.getHeadImg());
                    whUserUpdate.setKuaiNumber(whUserNew.getKuaiNumber());
                    whUserService.updateWhUser(whUserUpdate);
                    return success("验证成功，任务完成", whUser1);
                }

                whUser.setId(whUser.getKuaiId());
                whUser.setCreateTime(new Date());
                whUser.setNextReceiveTime(new Date());
                whUser.setIntegral(whzjBaseconfig.getFirstSend());
                whUser.setInvitationCode(StringUtils.getRandomString(6));
                whUser.setpCode("0");
                //根据父级邀请码查下父级是否存在
                String _pcode = null;
                String type = null;
                if(EmptyUtils.isNotEmpty(pCode)){
                    if(!pCode.contains(",")){
                        _pcode = pCode;
                    }else{
                        String pcodes[] = pCode.split(",");
                        _pcode = pcodes[0];
                        type = pcodes[1];
                    }

                    WhUser userP = whUserService.selectWhUserByCodeId(_pcode);
                    if(userP != null){
                        WhUser userP1 = new WhUser();
                        userP1.setId(userP.getId());
                        userP1.setKuaiId(userP.getKuaiId());
                        if("1".equals(type)){//拉新
                            whUser.setpCode(_pcode);
                            whUser.setpPCode(userP.getpCode());
                        }else{//分享

                            userP1.setIntegral(userP.getIntegral() + whzjBaseconfig.getShareSend());
                            //积分记录
                            WhIntegralHistory history = new WhIntegralHistory();
                            history.setId(IdWorker.getId());
                            history.setCreateTime(new Date());
                            history.setUserId(userP.getId());
                            history.setIntegral(whzjBaseconfig.getShareSend());
                            history.setEventId(null);
                            history.setOperat("11");
                            whIntegralHistoryService.insertWhIntegralHistory(history);


                            WhUserLittle little = new WhUserLittle();
                            little.setId(IdWorker.getId());
                            little.setUserid(userP.getId());
                            little.setKuaiid(whUser.getId());
                            whUserLittleService.insertWhUserLittle(little);
                        }

                        List<WhUser> list = whUserService.selectWhUserByPCode(_pcode);//判断分享的人够不够成功代理用户
                        if(list.size() >= whzjBaseconfig.getAutoRiselevel()){
                            userP1.setUserGroup("代理用户");
                            if(EmptyUtils.isEmpty(userP.getCommission())){
                                userP1.setCommission(whzjBaseconfig.getFirstDistrirate().toString());
                                userP1.setSecondDistirrate(whzjBaseconfig.getSecondDistirrate().toString());
                            }
                        }
                        whUserService.updateWhUser(userP1);



                    }
                }

                //积分记录
                WhIntegralHistory history = new WhIntegralHistory();
                history.setId(IdWorker.getId());
                history.setCreateTime(new Date());
                history.setUserId(whUser.getId());
                history.setIntegral(whzjBaseconfig.getFirstSend());
                history.setEventId(null);
                history.setOperat("12");
                whIntegralHistoryService.insertWhIntegralHistory(history);

                whUserService.insertWhUser(whUser);
            }else{
                WhTaskUser taskUser = new WhTaskUser();
                taskUser.setId(IdWorker.getId());
                taskUser.setUserId(whUser.getId());
                taskUser.setTaskId(taskId);
                taskUser.setCreateTime(new Date());
                taskUser.setWorkid(task.getWorkId());
                whTaskUserService.insertWhTaskUser(taskUser);
                WhUser user = new WhUser();
                user.setId(whUser.getId());
                user.setHeadImg(whUserNew.getHeadImg());
                user.setKuaiNumber(whUserNew.getKuaiNumber());
                List<WhTask> list = whTaskService.getWhTaskLogin(whUser.getId());
                if(list.size() == 0){
                    user.setCheckFlag("1");
                }
                whUserService.updateWhUser(user);

            }


            return success("验证成功，任务完成", whUser);
        }else{
            return error("验证失败，请重试");
        }

    }


    /**
     * 切换小号
     * @param number
     * @return
     * @throws Exception
     */
    @RequestMapping("/userLoginSwitch")
    @ResponseBody
    public synchronized AjaxResult userLoginSwitch(String number)throws Exception
    {
        WhUser whUser = whUserService.selectWhUserByKuaiId(number);
        if(whUser == null){
            return success("用户不存在");
        }
        return success("切换成功", whUser);
    }


    @RequestMapping("/test")
    @ResponseBody
    public AjaxResult test(String kuaiId)throws Exception{
        Map<String, Object> mapK = (Map<String, Object>) kMap.get(kuaiId);
        if(EmptyUtils.isEmpty(mapK)){
            String url = "aaa" + kuaiId;
            long time = System.currentTimeMillis();
            Map<String, Object> map = new HashMap<>();
            map.put("url", url);
            map.put("time", time);
            kMap.put(kuaiId, map);
        }
        String url = mapK.get("url").toString();
        long time = (long)mapK.get("time");
        long time1 = System.currentTimeMillis();
        if(time1 - time > 10 * 1000){
            mapK.put("time", time1);
            kMap.put(kuaiId, mapK);
        }

        System.out.println(url);

        return success("", kMap);
    }


    /**
     * 获取用户作品列表 -- 通过第三方接口获取
     * http://47.94.111.161:9106/api/v1/kuaishou/user/posts?token=0f400461-227b-45bc-98d2-bbdabb3f&eid=2111861224&pcursor=0
     * @param kuaiId
     * @return
     */
    @RequestMapping("/getUserWorkList")
    @ResponseBody
    public AjaxResult getUserWorkList(String kuaiId)throws Exception
    {
        try {
            List<Map<String, Object>> photoList = new ArrayList<>();
            int mixFeedsSize = 0;
            int i = 0;
            do {


                String url = "http://47.94.111.161:9106/api/v1/kuaishou/user/posts?token=0f400461-227b-45bc-98d2-bbdabb3f&eid="+kuaiId+"&pcursor="+i;
                i ++;
                String json = OkHttpUtil.get(url);
                System.out.println("返回结果---------------------" + json);
                JSONObject jsonObject = JSONObject.fromObject(json);
                System.out.println(jsonObject);


                Map<String, Object> data = (Map<String, Object>) jsonObject.get("data");
                List<Map<String, Object>> feeds = (List<Map<String, Object>>) data.get("feeds");
                System.out.println(data);
                mixFeedsSize = feeds.size();
                if (feeds.size() > 0) {

                    for (Map<String, Object> a : feeds) {
                        Map<String, Object> photo = new HashMap<>();
                        String photoId = a.get("photoId").toString();
                        Long timestamp = (Long)a.get("timestamp");

                            Map<String, Object> soundTrack = (Map<String, Object>) a.get("soundTrack");
                            List<Map<String, Object>> imageUrls = new ArrayList<>();
                            if(soundTrack != null){
                                imageUrls = (List<Map<String, Object>>) soundTrack.get("imageUrls");
                            }else{
                                imageUrls = (List<Map<String, Object>>) a.get("mainMvUrls");
                                if(imageUrls == null || imageUrls.size() == 0){
                                    imageUrls = (List<Map<String, Object>>) a.get("coverUrls");
                                }
                            }
                            Map<String, Object> coverUrl = imageUrls.get(0);
                            String imageUrl = coverUrl.get("url").toString();
                            photo.put("photoId", photoId);
                            photo.put("imageUrl", imageUrl);
                            photo.put("timestamp", timestamp);
                            photoList.add(photo);

                    }
                }
//            } while (mixFeedsSize != 0);
            } while (i > 1);




            Collections.sort(photoList, new Comparator<Map<String, Object>>(){
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    Long name1 =(Long)o1.get("timestamp");//name1是从你list里面拿出来的一个
                    Long name2= (Long)o2.get("timestamp"); //name1是从你list里面拿出来的第二个name
                    return name2.compareTo(name1);
                }
            });
            System.out.println("kMap-------------------------------------" + kMap);

            return success("操作成功", photoList);

        }catch (Exception e){
            e.printStackTrace();
            return error("暂未获取到作品，请刷新后重试");
        }
    }


    /**
     * 获取用户作品列表 -- 通过搜索获取作品列表
     * @param kuaiId
     * @return
     */
    @RequestMapping("/getUserWorkListOld2")
    @ResponseBody
    public AjaxResult getUserWorkListOld2(String kuaiId)throws Exception
    {
        try {
            List<Map<String, Object>> photoList = new ArrayList<>();
            int mixFeedsSize = 0;
            int i = 0;
            do {

                WhzjBaseconfig whzjBaseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");
                String[] svapis = whzjBaseconfig.getSvapi().split(",");
                Random random = new Random();//随机对象
                int n = random.nextInt(svapis.length);//随机一个整数
                String svapiId = svapis[n];
                String url = "http://182.254.153.170:8000/gifshow/search/new?infoId="+svapiId+"&proxyId=1&keyword=" + kuaiId + "&pCursor="+i;
                i ++;
                String json = OkHttpUtil.get(url);
                System.out.println("返回结果---------------------" + json);
                JSONObject jsonObject = JSONObject.fromObject(json);
                System.out.println(jsonObject);


                List<Map<String, Object>> mixFeeds = (List<Map<String, Object>>) jsonObject.get("mixFeeds");
                System.out.println(mixFeeds);
                mixFeedsSize = mixFeeds.size();
                if (mixFeeds.size() > 0) {

                    for (Map<String, Object> a : mixFeeds) {
                        Map<String, Object> feed = (Map<String, Object>) a.get("feed");
                        if(feed != null){
                            Map<String, Object> photo = new HashMap<>();
                            String photoId = feed.get("photo_id").toString();
                            Long timestamp = (Long)feed.get("timestamp");
                            String time = feed.get("time").toString();

                            if((System.currentTimeMillis() - timestamp) >= 30 * 24 * 60 * 60 * 1000) {
                                Map<String, Object> soundTrack = (Map<String, Object>) feed.get("soundTrack");
                                List<Map<String, Object>> imageUrls = new ArrayList<>();
                                if(soundTrack != null){
                                    imageUrls = (List<Map<String, Object>>) soundTrack.get("imageUrls");
                                }else{
                                    imageUrls = (List<Map<String, Object>>) feed.get("main_mv_urls");
                                    if(imageUrls == null || imageUrls.size() == 0){
                                        imageUrls = (List<Map<String, Object>>) feed.get("cover_urls");
                                    }
                                }
                                Map<String, Object> coverUrl = imageUrls.get(0);
                                String imageUrl = coverUrl.get("url").toString();
                                photo.put("photoId", photoId);
                                photo.put("imageUrl", imageUrl);
                                photo.put("timestamp", timestamp);
                                photoList.add(photo);
                            }

                        }
                    }
                }
            } while (mixFeedsSize != 0);




            Collections.sort(photoList, new Comparator<Map<String, Object>>(){
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    Long name1 =(Long)o1.get("timestamp");//name1是从你list里面拿出来的一个
                    Long name2= (Long)o2.get("timestamp"); //name1是从你list里面拿出来的第二个name
                    return name2.compareTo(name1);
                }
            });
            System.out.println("kMap-------------------------------------" + kMap);

            return success("操作成功", photoList);

        }catch (Exception e){
            e.printStackTrace();
            return error("暂未获取到作品，请刷新后重试");
        }
    }


    /**
     * 获取用户作品列表-- 直接获取作品列表 风控，暂时不用
     * @param kuaiId
     * @return
     */
    @RequestMapping("/getUserWorkListOld")
    @ResponseBody
    public AjaxResult getUserWorkListOld(String kuaiId)throws Exception
    {
        try {
            String url = "http://wx.zsyhtest.com/gifshow/feed/profile2?infoId=18&proxyId=1&uid="+ kuaiId;
            String json = OkHttpUtil.get(url);
            System.out.println("返回结果---------------------" + json);
            JSONObject jsonObject = JSONObject.fromObject(json);
            System.out.println(jsonObject);


            List<Map<String, Object>> feeds = (List<Map<String, Object>>) jsonObject.get("feeds");
            System.out.println(feeds);
            if (feeds.size() > 0) {
                List<Map<String, String>> photoList = new ArrayList<>();
                for (Map<String, Object> a : feeds) {
                    Map<String, String> photo = new HashMap<>();
                    String photoId = a.get("photo_id").toString();
                    String time = a.get("time").toString();
                    Long timestamp = (Long)a.get("timestamp");

                    if((System.currentTimeMillis() - timestamp) >= 30 * 24 * 60 * 60 * 1000) {
                        List<Map<String, Object>> coverUrls = (List<Map<String, Object>>) a.get("main_mv_urls");
                        if(coverUrls == null || coverUrls.size() == 0){
                            coverUrls = (List<Map<String, Object>>) a.get("cover_urls");
                        }
                        Map<String, Object> coverUrl = coverUrls.get(0);
                        String imageUrl = coverUrl.get("url").toString();
                        photo.put("photoId", photoId);
                        photo.put("imageUrl", imageUrl);
                        photoList.add(photo);
                    }


                }

                System.out.println("kMap-------------------------------------" + kMap);

                return success("操作成功", photoList);
            } else {
                return error("暂无作品，请刷新后重试");
            }
        }catch (Exception e){
            e.printStackTrace();
            return error("暂未获取到作品，请刷新后重试");
        }
    }

    /**
     * 判断用户是否点赞成功
     * @param kuaiId
     * @param photoId
     * @param taskId
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/judgIsGreat")
    @ResponseBody
    public synchronized AjaxResult judgIsGreat(String kuaiId, String photoId, String taskId, String userId)throws Exception
    {

        WhTask task = whTaskService.selectWhTaskById(taskId);
        int allNum = task.getAllNum();
        int num = task.getNum();
        if(allNum > num){
//            String url = "https://svapi.yokey.top/api/v1/?appId="+appId+"&appKey="+appKey+"&action=gifshow/moment/list&uid="+kuaiId+"&pCursor=";

            WhzjBaseconfig whzjBaseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");
            String[] svapis = whzjBaseconfig.getSvapi().split(",");
            Random random = new Random();//随机对象
            int n = random.nextInt(svapis.length);//随机一个整数
            String svapiId = svapis[n];
            String url = "http://182.254.153.170:8000/gifshow/moment/list?infoId="+svapiId+"&proxyId=1&uid="+kuaiId;
            String json = OkHttpUtil.get(url);

            System.out.println("返回结果---------------------"+json);

            boolean isContains = false;
            if(!json.contains(photoId)){
                String workId = task.getWorkId();
                String url1 = "http://47.94.111.161:9106/api/v1/kuaishou/user/photos/info?token=0f400461-227b-45bc-98d2-bbdabb3f&photoIds="+workId;
                String json1 = OkHttpUtil.get(url1);
                JSONObject jsonObject = JSONObject.fromObject(json1);
                Map<String, Object>  data = ( Map<String, Object>)jsonObject.get("data");
                Map<String, Object>  photos = ( Map<String, Object>) data.get("photos");
                Map<String, Object>  work = ( Map<String, Object>) photos.get(workId);
                Integer likeNum = (int) work.get("like_count");
                if(task.getLikeNum() < likeNum){
                    isContains = true;
                }
            }

            if(json.contains(photoId) || isContains){
                if(task != null){
                    //TODO
                    WhTasksetting setting = whTasksettingService.selectWhTasksettingById("1");
                    int reward = setting.getGreatReward();

                    //任务完成数量+1
                    WhTask task1 = new WhTask();
                    task1.setId(taskId);
                    task1.setNum(task.getNum() + 1);
                    if(num + 1 == allNum){
                        task1.setStatus("已完成");
                    }
                    whTaskService.updateWhTask(task1);

                    //修改用户积分
                    WhUser user = whUserService.selectWhUserById(userId);
                    WhUser user1 = new WhUser();
                    user1.setId(userId);
                    user1.setIntegral(user.getIntegral() + reward);
                    whUserService.updateWhUser(user1);

                    //保存积分明细
                    WhIntegralHistory integralHistory = new WhIntegralHistory();
                    integralHistory.setId(IdWorker.getId());
                    integralHistory.setCreateTime(new Date());
                    integralHistory.setUserId(userId);
                    integralHistory.setIntegral(reward);
                    integralHistory.setOperat("1");//完成双击任务
                    integralHistory.setEventId(taskId);

                    whIntegralHistoryService.insertWhIntegralHistory(integralHistory);

                    WhTaskUser taskUser = new WhTaskUser();
                    taskUser.setId(IdWorker.getId());
                    taskUser.setUserId(userId);
                    taskUser.setTaskId(taskId);
                    taskUser.setCreateTime(new Date());
                    taskUser.setWorkid(task.getWorkId());
                    whTaskUserService.insertWhTaskUser(taskUser);

                }



                return success("点赞成功，任务完成");
            }else{
                return error("点赞失败");
            }
        }
        return error("您晚了一步，任务做完了");

    }


    /**
     * 评论是否完成
     * @param kuaiId
     * @param photoId
     * @param taskId
     * @param userId
     * @param content
     * @return
     * @throws Exception
     */
    @RequestMapping("/commentIsGreat")
    @ResponseBody
    public synchronized AjaxResult commentIsGreat(String kuaiId, String photoId, String taskId, String userId, String content)throws Exception
    {

        WhTask task = whTaskService.selectWhTaskById(taskId);
        int allNum = task.getAllNum();
        int num = task.getNum();
        if(allNum > num){
//            String url = "https://svapi.yokey.top/api/v1/?appId="+appId+"&appKey="+appKey+"&action=gifshow/comment/list&uid="+kuaiId+"&photoId="+photoId+"&pCursor=";
            WhzjBaseconfig whzjBaseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");
            String[] svapis = whzjBaseconfig.getSvapi().split(",");
            Random random = new Random();//随机对象
            int n = random.nextInt(svapis.length);//随机一个整数
            String svapiId = svapis[n];
            String url = "http://182.254.153.170:8000/gifshow/comment/list?infoId="+svapiId+"&proxyId=1&uid="+kuaiId+"&photoId="+photoId;
//        String json = HttpUtils.sendGet(url, "");
//        String json = sendGet(url);

            long time = System.currentTimeMillis();
            String json = "";
            do{
                try {

                    long time1 = System.currentTimeMillis();
                    if(time1 - time > 55 * 1000){
                        return error("请求超时，请刷新后重试");
                    }

                    json = OkHttpUtil.get(url);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }while (EmptyUtils.isEmpty(json));

            System.out.println("返回结果---------------------"+json);
            if(json.contains(kuaiId)){
                if(task != null){

                    //获取评论内容
                    String _content = null;
                    JSONObject jsonObject = JSONObject.fromObject(json);
                    List<Map<String, Object>>  rootComments = (List<Map<String, Object>>)jsonObject.get("rootComments");
                    for(Map<String, Object> a:rootComments){
                        if(kuaiId.equals(String.valueOf(a.get("author_id")))){
                            _content = String.valueOf(a.get("content"));
                            if(StringUtils.isNotEmpty(content)){
                                if(content.equals(_content)){
                                    break;
                                }else{
                                    return error("评论失败，请删除之前评论，并复制评论内容直接评论");
                                }
                            }

                        }
                    }
                    System.out.println("评论内容----------------------------------------------------------------------" + _content);
                    //TODO
                    WhTasksetting setting = whTasksettingService.selectWhTasksettingById("1");
                    int reward = setting.getCommentReward();

                    //任务完成数量+1
                    WhTask task1 = new WhTask();
                    task1.setId(taskId);
                    task1.setNum(task.getNum() + 1);
                    if(num + 1 == allNum){
                        task1.setStatus("已完成");
                    }
                    whTaskService.updateWhTask(task1);

                    //修改用户积分
                    WhUser user = whUserService.selectWhUserById(userId);
                    WhUser user1 = new WhUser();
                    user1.setId(userId);
                    user1.setIntegral(user.getIntegral() + reward);
                    whUserService.updateWhUser(user1);

                    //保存积分明细
                    WhIntegralHistory integralHistory = new WhIntegralHistory();
                    integralHistory.setId(IdWorker.getId());
                    integralHistory.setCreateTime(new Date());
                    integralHistory.setUserId(userId);
                    integralHistory.setIntegral(reward);
                    integralHistory.setOperat("2");//完成评论任务
                    integralHistory.setEventId(taskId);

                    whIntegralHistoryService.insertWhIntegralHistory(integralHistory);


                    WhTaskUser taskUser = new WhTaskUser();
                    taskUser.setId(IdWorker.getId());
                    taskUser.setUserId(userId);
                    taskUser.setTaskId(taskId);
                    taskUser.setCreateTime(new Date());
                    taskUser.setContent(_content);
                    taskUser.setWorkid(task.getWorkId());
                    whTaskUserService.insertWhTaskUser(taskUser);

                }



                return success("评论成功，任务完成");
            }else{
                return error("评论失败");
            }
        }
        return error("您晚了一步，任务做完了");

    }


    /**
     * 判断用户是否关注成功
     * @param kuaiId
     * @param followedId
     * @param taskId
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/followIsGreat")
    @ResponseBody
    public synchronized AjaxResult followIsGreat(String kuaiId, String followedId, String taskId, String userId)throws Exception
    {

        WhTask task = whTaskService.selectWhTaskById(taskId);
        int allNum = task.getAllNum();
        int num = task.getNum();
        if(allNum > num){
//            String url = "https://svapi.yokey.top/api/v1/?appId="+appId+"&appKey="+appKey+"&action=gifshow/moment/list&uid="+kuaiId+"&pCursor=";
            WhzjBaseconfig whzjBaseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");
            String[] svapis = whzjBaseconfig.getSvapi().split(",");
            Random random = new Random();//随机对象
            int n = random.nextInt(svapis.length);//随机一个整数
            String svapiId = svapis[n];
            String url = "http://182.254.153.170:8000/gifshow/moment/list?infoId="+svapiId+"&proxyId=1&uid="+kuaiId;
//        String json = HttpUtils.sendGet(url, "");
//        String json = sendGet(url);

            long time = System.currentTimeMillis();
            String json = "";
            do{
                try {

                    long time1 = System.currentTimeMillis();
                    if(time1 - time > 55 * 1000){
                        return error("请求超时，请刷新后重试");
                    }

                    json = OkHttpUtil.get(url);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }while (EmptyUtils.isEmpty(json));


            System.out.println("返回结果---------------------"+json);
            if(json.contains(followedId)){
                if(task != null){
                    //TODO
                    WhTasksetting setting = whTasksettingService.selectWhTasksettingById("1");
                    int reward = setting.getAttentionReward();

                    //任务完成数量+1
                    WhTask task1 = new WhTask();
                    task1.setId(taskId);
                    task1.setNum(task.getNum() + 1);
                    if(num + 1 == allNum){
                        task1.setStatus("已完成");
                    }
                    whTaskService.updateWhTask(task1);

                    //修改用户积分
                    WhUser user = whUserService.selectWhUserById(userId);
                    WhUser user1 = new WhUser();
                    user1.setId(userId);
                    user1.setIntegral(user.getIntegral() + reward);
                    whUserService.updateWhUser(user1);

                    //保存积分明细
                    WhIntegralHistory integralHistory = new WhIntegralHistory();
                    integralHistory.setId(IdWorker.getId());
                    integralHistory.setCreateTime(new Date());
                    integralHistory.setUserId(userId);
                    integralHistory.setIntegral(reward);
                    integralHistory.setOperat("3");//完成关注任务
                    integralHistory.setEventId(taskId);

                    whIntegralHistoryService.insertWhIntegralHistory(integralHistory);


                    WhTaskUser taskUser = new WhTaskUser();
                    taskUser.setId(IdWorker.getId());
                    taskUser.setUserId(userId);
                    taskUser.setTaskId(taskId);
                    taskUser.setCreateTime(new Date());
                    taskUser.setWorkid(task.getWorkId());
                    whTaskUserService.insertWhTaskUser(taskUser);

                }



                return success("关注成功，任务完成");
            }else{
                return error("关注失败");
            }
        }
        return error("您晚了一步，任务做完了");

    }





    /**
     * 保存小号 --- 判断用户是否点赞成功
     * @param kuaiId
     * @param photoId
     * @param taskId
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/judgIsGreatTitleUser")
    @ResponseBody
    public synchronized AjaxResult judgIsGreatTitleUser(String kuaiId, String photoId, String taskId, String userId)throws Exception
    {
        WhUser whUser = getKIdByAll(kuaiId);

        if(whUser == null){
            whUser = getKId(kuaiId);
            if(whUser == null){
                return error("快手号不存在，请重试");
            }
        }

        String _kuaiId = whUser.getKuaiId();

        WhUser user = whUserService.selectWhUserById(userId);
        if("0".equals(user.getIsDisable())){
            return error("用户被封禁，请联系客服");
        }
        if(_kuaiId.equals(user.getKuaiId())){
            return error("添加的小号不能与当前快手号一致");
        }

        WhTask task = whTaskService.selectWhTaskById(taskId);
        int allNum = task.getAllNum();
        int num = task.getNum();

        WhzjBaseconfig whzjBaseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");
        String[] svapis = whzjBaseconfig.getSvapi().split(",");
        Random random = new Random();//随机对象
        int n = random.nextInt(svapis.length);//随机一个整数
        String svapiId = svapis[n];
        String url = "http://182.254.153.170:8000/gifshow/moment/list?infoId="+svapiId+"&proxyId=1&uid="+_kuaiId;
//        String url = "https://svapi.yokey.top/api/v1/?appId="+appId+"&appKey="+appKey+"&action=gifshow/moment/list&uid="+_kuaiId+"&pCursor=";


        long time = System.currentTimeMillis();
        String json = "";
        do{
            try {

                long time1 = System.currentTimeMillis();
                if(time1 - time > 55 * 1000){
                    return error("请求超时，请刷新后重试");
                }

                json = OkHttpUtil.get(url);
            }catch (Exception e){
                e.printStackTrace();
            }
        }while (EmptyUtils.isEmpty(json));


        System.out.println("返回结果---------------------"+json);
        if(json.contains(photoId)){
            if(task != null){

                WhUserLittle little = new WhUserLittle();
                little.setId(IdWorker.getId());
                little.setKuaiid(kuaiId);
                little.setUserid(userId);
                little.setCreateTime(new Date());
                whUserLittleService.insertWhUserLittle(little);


//                    //TODO
                WhTasksetting setting = whTasksettingService.selectWhTasksettingById("1");
                int reward = setting.getGreatReward();

                //任务完成数量+1
                WhTask task1 = new WhTask();
                task1.setId(taskId);
                task1.setNum(task.getNum() + 1);
                if(num + 1 == allNum){
                    task1.setStatus("已完成");
                }
                whTaskService.updateWhTask(task1);



            }



            return success("点赞成功，任务完成");
        }else{
            return error("点赞失败");
        }

    }

    /**
     * 添加小号
     * @param kuaiId
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/saveTitleUser")
    @ResponseBody
    public synchronized AjaxResult saveTitleUser(String kuaiId, String userId)throws Exception
    {
            WhUserLittle little = new WhUserLittle();
            little.setId(IdWorker.getId());
            little.setKuaiid(kuaiId);
            little.setUserid(userId);
            little.setCreateTime(new Date());
            whUserLittleService.insertWhUserLittle(little);

            return success("点赞成功，任务完成");

    }


    /**
     * 获取小号
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getUserLittle")
    @ResponseBody
    public synchronized AjaxResult getUserLittle(String userId)throws Exception
    {
        WhUserLittle little = new WhUserLittle();
        little.setUserid(userId);
        return success("点赞成功，任务完成", whUserLittleService.selectWhUserLittleList(little));

    }

    /**
     * 通过搜索选项卡用户 获取快手id
     * @param number
     * @return
     * @throws Exception
     */
    public WhUser getKId(String number)
    {

        try{
            WhUser whUser = whUserService.selectWhUserByKuaiId(number);

            if(whUser != null)return whUser;

            whUser = whUserService.selectWhUserByKuaiNumber(number);
            if(whUser != null)return whUser;

            WhzjBaseconfig whzjBaseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");
            String[] svapis = whzjBaseconfig.getSvapi().split(",");
            Random random = new Random();//随机对象
            int n = random.nextInt(svapis.length);//随机一个整数
            String svapiId = svapis[n];

//        String url = "https://svapi.yokey.top/api/v1/?appId="+appId+"&appKey="+appKey+"&action=gifshow/search/user&keyword="+number+"&pCursor=&usSid=";
            String url = "http://182.254.153.170:8000/gifshow/search/user?infoId="+svapiId+"&proxyId=1&keyword="+number;

            long time = System.currentTimeMillis();
            String json = "";
            String kuaiUserId = "";
            String kwaiId = "";
            whUser = new WhUser();
            do{
                try {

//                Robot r = new Robot();
//                System.out.println("延时前:" + new Date().toString());
//                r.delay(1000);
                    System.out.println("延时后:" + new Date().toString());

                    long time1 = System.currentTimeMillis();
                    if(time1 - time > 55 * 1000){
                        return null;
                    }

                    json = OkHttpUtil.get(url);

                    JSONObject jsonObject = JSONObject.fromObject(json);
                    List<Map<String, Object>>  users = ( List<Map<String, Object>>)jsonObject.get("users");
                    if(users.size() == 0){
                        return null;
                    }
                    kuaiUserId = String.valueOf(users.get(0).get("user_id"));//快手id
                    kwaiId = String.valueOf(users.get(0).get("kwaiId"));//快手号
                    String headurl = String.valueOf(users.get(0).get("headurl"));
                    String user_name = String.valueOf(users.get(0).get("user_name"));

                    whUser.setHeadImg(headurl);
                    whUser.setNickname(user_name);
                    whUser.setKuaiId(kuaiUserId);
                    if(EmptyUtils.isNotEmpty(kwaiId)){
                        whUser.setKuaiNumber(kwaiId);
                    }else{
                        whUser.setKuaiNumber(kuaiUserId);
                    }

                    System.out.println(kuaiUserId);
                    if(!kuaiUserId.equals(number) && !kwaiId.equals(number)){
                        return null;
                    }
//                Robot r1 = new Robot();
//                System.out.println("延时前:" + new Date().toString());
//                r1.delay(4 * 1000);
                    System.out.println("延时后:" + new Date().toString());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }while (EmptyUtils.isEmpty(kuaiUserId));


            System.out.println("返回结果---------------------"+json);



            return whUser;
        }catch (Exception e){
            e.printStackTrace();

        }
        return null;
    }


    /**
     * 搜索选项卡综合 -- 获取用户id
     * @param number
     * @return
     * @throws Exception
     */
    public WhUser getKIdByAll(String number)throws Exception {

//        String url = "https://svapi.yokey.top/api/v1/?appId="+appId+"&appKey="+appKey+"&action=gifshow/search/new&keyword="+number+"&pCursor=&usSid=";

        try{
            WhzjBaseconfig whzjBaseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");
            String[] svapis = whzjBaseconfig.getSvapi().split(",");
            Random random = new Random();//随机对象
            int n = random.nextInt(svapis.length);//随机一个整数
            String svapiId = svapis[n];

            String url = "http://182.254.153.170:8000/gifshow/search/new?infoId="+svapiId+"&proxyId=1&keyword=" + number;


            long time = System.currentTimeMillis();
            String json = "";
            String kuaiUserId = "";
            String kwaiId = "";
            WhUser whUser = new WhUser();
            do {
                try {
//                Robot r = new Robot();
//                System.out.println("延时前:" + new Date().toString());
//                r.delay(1000);
                    System.out.println("延时后:" + new Date().toString());

                    long time1 = System.currentTimeMillis();
                    if (time1 - time > 55 * 1000) {
                        return null;
                    }

                    json = OkHttpUtil.get(url);

                    JSONObject jsonObject = JSONObject.fromObject(json);
                    List<Map<String, Object>> aladdins = (List<Map<String, Object>>) jsonObject.get("aladdins");
                    String users = aladdins.get(0).get("user").toString();
                    JSONObject user = JSONObject.fromObject(users);
                    kuaiUserId = String.valueOf(user.get("user_id"));//快手id
                    kwaiId = String.valueOf(user.get("kwaiId"));//快手号
                    String headurl = String.valueOf(user.get("headurl"));
                    String user_name = String.valueOf(user.get("user_name"));

                    whUser.setHeadImg(headurl);
                    whUser.setNickname(user_name);
                    whUser.setKuaiId(kuaiUserId);
                    if (EmptyUtils.isNotEmpty(kwaiId)) {
                        whUser.setKuaiNumber(kwaiId);
                    } else {
                        whUser.setKuaiNumber(kuaiUserId);
                    }
                    System.out.println(kuaiUserId);
                    if (!kuaiUserId.equals(number) && !kwaiId.equals(number)) {
                        return null;
                    }
//                Robot r1 = new Robot();
//                System.out.println("延时前:" + new Date().toString());
//                r1.delay(4 * 1000);
                    System.out.println("延时后:" + new Date().toString());

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } while (EmptyUtils.isEmpty(kuaiUserId));


            System.out.println("返回结果---------------------" + json);


            return whUser;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;

    }



}

